package com.yuwen.yuwenRPC.server.tcp;

/**
 * @ClassNameTCPServerHandler
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/2 下午9:22
 * @Version 1.0
 **/
import com.yuwen.yuwenRPC.model.RpcRequest;
import com.yuwen.yuwenRPC.model.RpcResponse;
import com.yuwen.yuwenRPC.protocol.ProtocolMessage;
import com.yuwen.yuwenRPC.protocol.ProtocolMessageDecoder;
import com.yuwen.yuwenRPC.protocol.ProtocolMessageEncoder;
import com.yuwen.yuwenRPC.protocol.ProtocolMessageTypeEnum;
import com.yuwen.yuwenRPC.registry.LocalRegistry;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;

import io.vertx.core.net.NetSocket;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * TCP 处理器
 */
public class TCPServerHandler implements Handler<NetSocket> {
    //处理链接
    @Override
    public void handle(NetSocket netSocket) {
        TCPBufferHandlerWrapper tcpBufferHandlerWrapper= new TCPBufferHandlerWrapper(buffer->{
            //接受请求
            ProtocolMessage<RpcRequest> protocolMessage;
            try {
                protocolMessage = (ProtocolMessage<RpcRequest>) ProtocolMessageDecoder.decode(buffer);
            } catch (IOException e) {
                throw new RuntimeException("协议消息解码错误");
            }
            RpcRequest rpcRequest = protocolMessage.getBody();
            //处理请求
            //构造响应结果对象
            RpcResponse rpcResponse = new RpcResponse();
            try {
                Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
                Method method = implClass.getMethod(rpcRequest.getMethodName(),rpcRequest.getParameterTypes());
                Object[] params = rpcRequest.getParameters();
                //获取结果
                Object result = method.invoke(implClass.newInstance(),params);
                //封装返回结果
                rpcResponse.setData(result);
                rpcResponse.setReturnType(method.getReturnType());
                rpcResponse.setMessage("ok");
            } catch (Exception e) {
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }
            //发送响应，编码
            ProtocolMessage.Header header = protocolMessage.getHeader();
            header.setType((byte)ProtocolMessageTypeEnum.RESPONSE.getKey());
            ProtocolMessage<RpcResponse> responseProtocolMessage = new ProtocolMessage<>(header,rpcResponse);

            try {
                Buffer encode = ProtocolMessageEncoder.encode(responseProtocolMessage);
                netSocket.write(encode);
            } catch (IOException e) {
                throw new RuntimeException("协议消息编码错误");
            }


        });
        netSocket.handler(tcpBufferHandlerWrapper);
    }
}
